//路由等权限管理
import router from './router'
import { setToken, getToken, getMenus, getSiteInfo, getUserInfo} from "@/utils/storage"
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
const whiteList = ['/VRLocPreview'] // 不需要token权限页面白名单


let baseUrl = store.getters.baseUrl
router.beforeEach( async(to,from,next) => {
    NProgress.start()
    // 首先判断是否有站点信息，获取后在进行判断(BUG 站点信息修改不更新问题)
    document.title = process.env.VUE_APP_TITLE
    let siteInfo
    if (whiteList.indexOf(to.path) == -1) {
      siteInfo = getSiteInfo()
      if(!siteInfo) await store.dispatch('app/setSiteInfo')
    }
    // 首先判断有无token，有token再判断是否有菜单，没有则判断url是否携带code？
    const hasToken = getToken()
    if(hasToken){
        const menus = getMenus()
        const userInfo = getUserInfo()
        if(menus?.length > 0 && userInfo){
            if(to.path === '/'){
              next({path: '/VRCenter/VRSceneList'})
            }else if(to.query?.code){
              // 去除url中的code，防止重新登录bug
              next({path: to.path}) 
            }else{
              next()
            }
            store.commit('app/CLOSE_SIDEBAR')
        }else{
            await store.dispatch('user/resetToken')
            await store.dispatch('user/initLogin')
            next({path: to.path})
        }
    }else{
      if (whiteList.indexOf(to.path) !== -1) {
        // 在白名单的直接跳转
        next()
      }else{
        const code = to.query.code
        if(code){
            setToken(code)
            next({path: to.path})
        }else{
          window.location.href = `${baseUrl}/login/index?redirect=${location.href}` 
        }
      }
    }
})
router.afterEach(() => {
    NProgress.done()
})
